package net.lovesrc.allin.jobs.base;

import com.zhouzhou.fastjava.http.HttpException;
import com.zhouzhou.fastjava.util.ThreadKit;
import net.lovesrc.allin.biz.BaseService;
import org.apache.commons.lang3.RandomUtils;

public abstract class BaseJob extends BaseService implements Runnable {

    @Override
    public final void run() {
        for (; ; ) {
            try {
                if (enable() && runFlag()) {
                    runOnce();
                }
            } catch (Exception e) {
                logger.error("run job error", e);
                if (e instanceof HttpException) {
                    // continue
                    sendNotificationToAdmin(e);
                } else {
                    endJob(e.getMessage());
                }
            } finally {
                long intervalMilliseconds = intervalMilliseconds();
                if (intervalMilliseconds <= 0) {
                    // nothing to do
                } else {
                    ThreadKit.sleepMilliseconds(intervalMilliseconds);
                }
            }
        }
    }

    public boolean runFlag() {
        return true;
    }


    public final boolean enable() {
        return tryGetProperties(boolean.class, false, "Job." + this.getClass().getSimpleName());
    }

    public abstract void runOnce() throws Exception;

    protected long intervalMilliseconds() {
        return RandomUtils.nextInt(100, 500);
    }

    protected final void endJob(String text) {
        this.justEndJob();
        String subject = getClass().getSimpleName() + " 已结束，" + text;
        this.sendNotificationToAdmin(subject, subject);
    }

    protected final void justEndJob() {
        this.updateSysConfig("Job." + getClass().getSimpleName(), false);
    }


}
